import axios from 'axios'
const route_base_url = process.env.VUE_APP_BASE_API_JSON
// process.env.NODE_ENV === 'development' ? '/' : process.env.VUE_APP_ROUTER_BASE

let jsonCacheController = {}

export function getJsonCacheController(jsonName) {
  const url = `${process.env.NODE_ENV === 'development' ? '' : '/portal'}/mock/${jsonName}.json`.replace('//', '/')
  axios.get(url).then((response) => {
    if (response.status !== 200) return
    jsonCacheController = response.data
    localStorage.setItem(`${jsonName}-samr-portal-admin-ui`, JSON.stringify(response.data))
  })
}

export function loadJsonFile2Cache(jsonName) {
  const jsonUpdateDate = `${jsonName}_updateDate`
  const jsonUpdateTime = localStorage.getItem(jsonUpdateDate) || ''
  if (jsonUpdateTime !== jsonCacheController[jsonUpdateDate]) {
    const xhr = new XMLHttpRequest()
    const url = `${route_base_url}/mock/${jsonName}.json`.replace('//', '/')
    xhr.open('GET', url, false)
    xhr.onreadystatechange = function() {
      if (xhr.status === 200) {
        localStorage.setItem(jsonName, xhr.responseText)
        localStorage.setItem(jsonUpdateDate, jsonCacheController[jsonUpdateDate])
      } else {
        alert('加载字典数据错误')
      }
    }
    xhr.send()
  }
}

export function getValue(dictType, label) { // 根据字典类型以及标签值获取对应的value值
  if (!dictType) return ''
  if (!label) return ''
  const dictData = getDictDataByType(dictType)
  if (Array.isArray(dictData)) {
    let value = ''
    for (let i = 0; i < dictData.length; i++) {
      if (label === dictData[i].label) {
        value = dictData[i].value
        break
      }
    }
    return value
  }
  return ''
}

export function getLabel(dictType, value) { // 根据字典类型以及value值获取对应的标签值
  if (!dictType) return ''
  if (!value) return ''
  const dictData = getDictDataByType(dictType)
  if (Array.isArray(dictData)) { // 数组
    let label = ''
    for (let i = 0; i < dictData.length; i++) {
      if (value === dictData[i].value) {
        label = dictData[i].label
        break
      }
    }
    return label
  }
  return ''
}

export function getDictDataByType(dictType) { // 根据类型获取对应的字典数据
  if (!dictType) {
    return []
  }
  const dictData = getCacheJson('dict' + '-samr-portal-admin-ui')
  return dictData[dictType] || []
}

export function getDictDataByTypeCustom(dictType) { // 根据类型获取对应的字典数据
  if (!dictType) {
    return []
  }
  const dictData = getCacheJson('dictCustom' + '-samr-portal-admin-ui')
  return dictData[dictType] || []
}

export function getCacheJson(key) { // 获取缓存的json对象
  if (!key) {
    return []
  }
  const jsonStr = localStorage.getItem(key)
  if (!jsonStr) {
    return []
  }
  return JSON.parse(jsonStr)
}

// 官方码表
getJsonCacheController('dict')
// 自定义码值
getJsonCacheController('dictCustom')

